package com.sgb.kjwl.utils;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;

import java.lang.ref.WeakReference;

/**
 * @author: 杨畔
 * @date: 2021/1/21 16:46
 * @Description: 延迟输入监听，防止输入回调频繁调用
 */
public abstract class CustomTextWatcher implements TextWatcher {
    private WeakReference<Handler> handler = new WeakReference<>(getHandler());

    private Handler getHandler() {
        return new Handler(msg -> {
            delayedChanged((Editable) msg.obj);
            return true;
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (handler.get() == null) {
            handler = new WeakReference<>(getHandler());
        }
        //移除200ms上次输入的内容
        handler.get().removeMessages(Message.obtain().what);
        //设置新内容
        Message msg = Message.obtain();
        msg.obj = s == null ? "" : s;
        handler.get().sendMessageDelayed(msg, 200);
    }

    /**
     * 延迟文字变化，防止请求频繁
     */
    protected abstract void delayedChanged(Editable content);
}
